package com.jerry.boot.core.mvc;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.AbstractMappingJacksonResponseBodyAdvice;

@ControllerAdvice
@Slf4j
public class JWebResponseBodyAdvice extends AbstractMappingJacksonResponseBodyAdvice {
    @Override
    protected void beforeBodyWriteInternal(MappingJacksonValue bodyContainer, MediaType contentType, MethodParameter returnType, ServerHttpRequest request, ServerHttpResponse response) {
        //标记了直接返回，不进行包装
        if (returnType.getMethodAnnotation(NativeResponse.class) != null) {
            return;
        }
        Object result = bodyContainer.getValue();
        if (!(result instanceof JsonResult)) {
            JsonResult jsonResult = JsonResult.create();
            int status = ((ServletServerHttpResponse) response).getServletResponse().getStatus();
            if (HttpStatus.OK.value() == status) {
                jsonResult.setCode(0);
                jsonResult.setData(result);
            } else {
                jsonResult.setCode(500);
            }
            bodyContainer.setValue(jsonResult);
        }
    }
}
